﻿using BCCommon;
using BCCommon.Enums;
using BCCommon.ExceptionExtensions;
using BCDto.UploadHandleComponent;
using BCEntity.Common;
using BCService.Common.WebsiteConfigurationService;
using BCService.UploadHandleComponent;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;

namespace BCTMSRESTful.Controllers.Management.WeChat
{
    /// <summary>
    /// 下载控制器
    /// </summary>
    [ApiExplorerSettings(GroupName = "Admin")]
    [Route("api/v1/sim/[controller]")]
    public class DownloadController : ManagementBaseController
    {
        private readonly IConfiguration configuration;
        private readonly IUploadFileInfoHandleService uploadFileInfoHandleService;
        private readonly IUploadHandleService uploadHandleService;
        private readonly IWebsiteConfigurationService websiteConfigurationService;
        public DownloadController(IConfiguration configuration,
            IUploadFileInfoHandleService uploadFileInfoHandleService,
            IUploadHandleService uploadHandleService, 
            IWebsiteConfigurationService websiteConfigurationService)
        {
            this.configuration = configuration;
            this.uploadFileInfoHandleService = uploadFileInfoHandleService;
            this.uploadHandleService = uploadHandleService;
            this.websiteConfigurationService = websiteConfigurationService;
        }

        #region 微信图文内图片下载并保存微信图文图片
        /// <summary>
        /// 微信图文内图片下载并保存微信图文图片。
        /// </summary>
        /// <param name="downloadBaseEntity">下载对象集合</param>
        /// <response code="200">上传微信文内图片结果。</response>
        /// <returns></returns>
        [HttpPost("[action]")]
        [ProducesResponseType(typeof(DownloadBaseEntity), 200)]
        public IActionResult DownloadImageUploadWechatNews([FromBody]DownloadBaseEntity downloadBaseEntity)
        {
            foreach(DownloadEntity request in downloadBaseEntity.list)
            {
                if (request.Address == null)
                {
                    return this.BadRequest("下载地址不能为空！");
                }
                string fileSuffix = Path.GetExtension(request.Address).ToLower();
                

                UploadFileDto uploadFileDto = uploadFileInfoHandleService.Init(request.Address, "WeChat", ".jpg");

                uploadFileDto.RemarkType = UploadFileRemarkType.WeChatNewsMaterial;
                Dictionary<string, object> remarkJSON = new Dictionary<string, object>();
                remarkJSON.Add("material_title", uploadFileDto.FullName);
                remarkJSON.Add("material_description", uploadFileDto.FullName);
                uploadFileDto.Remarks = remarkJSON;

                using (WebClient webClient = new WebClient())
                {
                    webClient.DownloadFileTaskAsync(request.Address, uploadFileDto.FilePath).GetAwaiter().GetResult();
                    using (FileStream fs = new FileStream(uploadFileDto.FilePath, FileMode.Open, FileAccess.Read))
                    {
                        var br = new BinaryReader(fs);
                        if (uploadFileDto.FolderName == "image")
                        {
                            CheckFileSecurity(br);
                        }
                        byte[] bytes = br.ReadBytes((int)fs.Length);
                        uploadFileDto.Content = bytes;
                        uploadFileDto.ContentLength = fs.Length;
                    }
                }

                UploadResponseDto uploadResponseDto = uploadHandleService.UploadHandle(uploadFileDto);
                uploadResponseDto.Src = uploadFileDto.Src;
                uploadResponseDto.Host = configuration["CurrentlyImageHost"];
                request.WechatHttp = uploadResponseDto.Message;
                request.ResultHttp =uploadResponseDto.Host + uploadResponseDto.Src;
            }
            
            return this.Ok(downloadBaseEntity);
        }

        /// <summary>
        /// 文件安全检查
        /// </summary>
        /// <param name="br">二进制字节流</param>
        private void CheckFileSecurity(BinaryReader br)
        {
            string fileClass;
            byte buffer;
            byte[] b = new byte[2];
            buffer = br.ReadByte();
            b[0] = buffer;
            fileClass = buffer.ToString();
            buffer = br.ReadByte();
            b[1] = buffer;
            fileClass += buffer.ToString();
            Dictionary<string, string> securityCode = new Dictionary<string, string>();
            //7790是Exe,8297是rar
            securityCode.Add("255216", "jpg");
            securityCode.Add("7173", "gif");
            securityCode.Add("6677", "BMP");
            securityCode.Add("13780", "PNG");
            if (!securityCode.Any(p => p.Key.Equals(fileClass)))
            {
                throw new UploadFileException("此文件不允许下载。");
            }
        }
        #endregion
    }
}